<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <style>
    h1 {
      text-align: center;
      width: 100%;
      color: rgb(212, 166, 105);
      font-size: 80px;
    }
    body {
      margin: 0;
      padding: 0;
      font-family: Arial, sans-serif;
    }
    input {
      margin: 10px 0;
      padding: 10px;
      border: 1px solid #ccc;
      width: 800px;
      margin-left: calc(50% - 400px);
    }
    ul {
      list-style: none;
      height: 800px;
      overflow-y: scroll;
      margin: 0;
      padding: 0;
      width: 800px;
      margin-left: calc(50% - 400px);
      scrollbar-width: thin;
      scrollbar-color: #ccc transparent;
    }
    li {
      margin: 10px 0;
      padding: 10px;
      border: 1px solid #ccc;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  </style>
  <body>
    <h1>Things</h1>
    <input type="text" id="txt" placeholder="添加一个待办事项" />
    <ul id="ul"></ul>
  </body>
  <script>
    function createLi(content) {
      ul.innerHTML += `<li><span>${content}</span><button>删除</button></li>`;
    }
    var txt = document.querySelector("#txt");
    var ul = document.querySelector("#ul");
    ul.innerHTML = "<li>没有待办事项</li>";
    txt.addEventListener("keydown", function (e) {
      if (e.key === "Escape") {
        this.value = "";
      }
      if (e.key === "Enter" && this.value.trim() !== "") {
        if (ul.children.length === 1) {
          if (ul.children[0].innerHTML === "没有待办事项") {
            ul.innerHTML = "";
          }
        }
        console.log("添加事件到列表");
        // 生成一个li元素
        createLi(this.value);
        this.value = "";
      }
    });

    // 使用事件委托的方式，给ul添加点击事件
    ul.addEventListener("click", function (e) {
      if (e.target.tagName === "BUTTON") {
        e.target.parentElement.remove();
      }
      if (ul.children.length === 0) {
        ul.innerHTML = "<li>没有待办事项</li>";
      }
    });
  </script>
</html>
